package cn.edu.lingnan.service.impl;

import cn.edu.lingnan.mapper.DepartmentMapper;
import cn.edu.lingnan.service.DepartmentService;
import cn.edu.lingnan.entity.pojo.Department;
import cn.edu.lingnan.entity.vo.DepartmentVO;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class DepartmentServiceImpl implements DepartmentService {

    @Autowired
    private DepartmentMapper departmentMapper;

    @Override
    public List<DepartmentVO> getHierarchy() {
        List<Department> departments = departmentMapper.selectList(null);
        return buildTree(departments, 0);
    }

    /**
     * 构建部门树
     * @param departments
     * @param parentId
     * @return
     */
    private List<DepartmentVO> buildTree(List<Department> departments, Integer parentId) {
        List<DepartmentVO> result = new ArrayList<>();
        for (Department department : departments) {
            if (parentId.equals(department.getParentDeptId())) {
                DepartmentVO vo = new DepartmentVO();
                BeanUtils.copyProperties(department, vo);
                vo.setChildren(buildTree(departments, department.getDeptId()));
                result.add(vo);
            }
        }
        return result;
    }


    @Override
    public void addDepartment(DepartmentVO departmentVO) {
        Department department = new Department();
        BeanUtils.copyProperties(departmentVO, department);
        departmentMapper.insert(department);
    }


    @Override
    public void deleteDepartmentById(Integer id) {
        // 递归删除子部门
        deleteChildren(id);
        // 删除前部门
        departmentMapper.deleteById(id);
    }

    private void deleteChildren(Integer parentId) {
        QueryWrapper<Department> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("parent_dept_id", parentId);
        List<Department> children = departmentMapper.selectList(queryWrapper);
        for (Department child : children) {
            deleteChildren(child.getDeptId());
            departmentMapper.deleteById(child.getDeptId());
        }
    }
}
